<?php

namespace App\Http\Controllers\Api\Login;

use App\Services\Api\Login\UserService;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 小程序用户静默登录
     * 颁布idtoken，防止userid直接传递给前端
     * @return \Illuminate\Http\JsonResponse
     */
    public function slient (){
        try {
            $code = request()->post('code');
            $res = UserService::slient($code);
            if (!$res){
                throw new \Exception('静默登录失败');
            }
            if (session('slient_state') == 'other'){
                return $this->success(200,'first_ok',$res);
            }
            return $this->success(200,'other_ok',$res);
        } catch (\Exception $exception){
            return $this->success(2001,$exception->getMessage());
        }
    }

    /**
     * 小程序授权登录
     * @return \Illuminate\Http\JsonResponse
     */
    public function mandate (){
        try {
            $data = request()->all();
            $res = UserService::mandate($data);
            if (!$res){
                throw new \Exception('授权失败');
            }
            return $this->success(200,'授权成功');
        } catch (\Exception $exception){
            return $this->success(2001,$exception->getMessage());
        }
    }

    public function mobile (){
        try {
            $data = request()->all();
            $res = UserService::mobile($data);
            if (!$res){
                throw new \Exception('登录失败');
            }
            return $this->success(200,'登录成功');
        } catch (\Exception $exception){
            return $this->success(2001,$exception->getMessage());
        }
    }

    public function captcha (){
        try {
            $tel = request()->post('tel');
            UserService::captcha($tel);
            return $this->success(200,'短信发送成功');
        } catch (\Exception $exception){
            return $this->success(2001,$exception->getMessage());
        }
    }

//    public function demo (){
//        $res = UserService::createToken(1);
//        echo $res;
//    }
}
